package com.imooc.sell.controller;

import com.imooc.sell.config.ProjectUrlConfig;
import com.imooc.sell.constant.CookieConstant;
import com.imooc.sell.constant.RedisConstant;
import com.imooc.sell.dataobject.SellerInfo;
import com.imooc.sell.enums.ResultEnum;
import com.imooc.sell.exception.SellException;
import com.imooc.sell.form.SellerInfoForm;
import com.imooc.sell.service.SellerService;
import com.imooc.sell.utils.CookieUtil;
import com.imooc.sell.utils.KeyUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/seller")
public class SellerUserController {

    @Autowired
    private SellerService sellerService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProjectUrlConfig projectUrlConfig;

    @GetMapping("/login")
    public ModelAndView login(@RequestParam("openid") String openid,
                              HttpServletResponse reponse,
                              Map<String, Object> map){
//        1.获取openid去和数据库里的数据匹配
        SellerInfo sellerInfo = sellerService.findSellerInfoByOpenid(openid);
        if (sellerInfo == null){
            map.put("msg", ResultEnum.LOGIN_FAIL.getMessage());
            map.put("url", "/sell/seller/order/list");
            return new ModelAndView("common/error");
        }
//        2.设置token至redis
        String token = UUID.randomUUID().toString();
        Integer expire = RedisConstant.EXPIRE;
        redisTemplate.opsForValue().set(String.format(RedisConstant.TOKEN_PREFIX, token), openid, expire, TimeUnit.SECONDS);
//        redisTemplate.opsForValue().set("whf","whfoxxx");

//        3.设置token至cookie,用工具类
        CookieUtil.set(reponse, CookieConstant.TOKEN, token, expire);
//        Cookie cookie = new Cookie("token",token);
//        cookie.setPath("/");
//        cookie.setMaxAge(7200);
//        reponse.addCookie(cookie);

//        跳转的路径最好写绝对路径
        return new ModelAndView("redirect:"+ projectUrlConfig.getSell() + "/sell/seller/order/list");
//        return new ModelAndView("redirect:"+ projectUrlConfig.getSell() + "/sell/seller/login");

    }


    @GetMapping("/logout")
    public ModelAndView logout(HttpServletRequest request,
                       HttpServletResponse response,
                       Map<String, Object> map){

//        1.从cookie中查询
        Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);
        if(cookie!=null){
//            2.清除redis；
            redisTemplate.opsForValue().getOperations().delete(String.format(RedisConstant.TOKEN_PREFIX, cookie.getValue()));
//            3.清除cookie,直接重新设置
            CookieUtil.set(response, CookieConstant.TOKEN,null,0);
        }
        map.put("msg",ResultEnum.LOGOUT_SUCCESS.getMessage());
        map.put("url","/sell/seller/order/list");
        return new ModelAndView("common/success",map);

    }
    @GetMapping("/checklogin")
    public ModelAndView checkLogin(Map<String, Object> map){
       // map.put("url","/sell/seller/common/login");
        return new ModelAndView("common/login",map);
    }

    @PostMapping("/mylogin")
    public ModelAndView myLogin(@Valid SellerInfoForm form,
                                BindingResult bindingResult,
                                Map<String, Object> map){
        if (bindingResult.hasErrors()){
            map.put("msg", bindingResult.getFieldError().getDefaultMessage());
            map.put("url", "/sell/seller/mylogin");
            return new ModelAndView("common/error",map);
        }
        SellerInfo sellerInfo = new SellerInfo();
//        productService.findOne(form.getProductId());
        try{
            //如果productId是空的说明是新增的
            if(!StringUtils.isEmpty(form.getSellerId())){
                sellerInfo = sellerService.findSellerInfoByOpenid(form.getSellerId());
            }else{
                form.setSellerId(KeyUtil.getUniqueKey());
            }
            BeanUtils.copyProperties(form, sellerInfo);
            sellerService.save(sellerInfo);
        }catch (SellException e){
            map.put("msg", e.getMessage());
            map.put("url", "/sell/seller/mylogin");
            return new ModelAndView("common/error", map);
        }
        map.put("url", "/sell/seller/mylogin");
        return new ModelAndView("common/success",map);
    }
}
